import {ipcMain, IpcMainInvokeEvent} from 'electron'
import {setupTabIpcHandlers} from "./tabHandler.ts";
import {setupStoreIpcHandlers} from "./storeHandler.ts";
import { logger, LogCategory } from '../logger';

/**
 * IPC处理服务类
 * 负责管理所有IPC通信的注册和移除
 */
export class IpcService {
  private static instance: IpcService;
  private handlers: string[] = [];

  private constructor() {
    logger.info('IpcService', LogCategory.IPC, 'IPC服务初始化');
  }

  /**
   * 获取IpcService单例
   */
  public static getInstance(): IpcService {
    if (!IpcService.instance) {
      IpcService.instance = new IpcService();
    }
    return IpcService.instance;
  }

  /**
   * 添加IPC处理程序
   * @param channel 通道名称
   * @param handler 处理函数
   */
  public addHandler(channel: string, handler: (event: IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void {
    try {
      logger.debug('IpcService', LogCategory.IPC, `注册IPC处理程序: ${channel}`);
      ipcMain.handle(channel, handler);
      this.handlers.push(channel);
    } catch (error) {
      logger.error('IpcService', LogCategory.IPC, `注册IPC处理程序失败: ${channel}`, error);
      throw new Error(`注册IPC处理程序失败: ${channel} - ${error}`);
    }
  }

  /**
   * 设置所有IPC处理程序
   */
  public setupHandlers(): void {
    try {
      logger.info('IpcService', LogCategory.IPC, '设置所有IPC处理程序');
      // 注册标签页处理程序
      setupTabIpcHandlers();
      // 注册存储处理程序
      setupStoreIpcHandlers();
      logger.info('IpcService', LogCategory.IPC, '所有IPC处理程序设置完成');
    } catch (error) {
      logger.error('IpcService', LogCategory.IPC, '设置IPC处理程序失败', error);
      throw new Error(`设置IPC处理程序失败: ${error}`);
    }
  }

  /**
   * 移除所有IPC处理程序
   */
  public removeHandlers(): void {
    try {
      logger.info('IpcService', LogCategory.IPC, `移除所有IPC处理程序, 数量: ${this.handlers.length}`);
      for (const channel of this.handlers) {
        logger.debug('IpcService', LogCategory.IPC, `移除IPC处理程序: ${channel}`);
        ipcMain.removeHandler(channel);
      }
      this.handlers = [];
      logger.info('IpcService', LogCategory.IPC, '所有IPC处理程序移除完成');
    } catch (error) {
      logger.error('IpcService', LogCategory.IPC, '移除IPC处理程序失败', error);
    }
  }
}

// 导出IPC服务实例
export const ipcService = IpcService.getInstance();

/**
 * 添加处理程序的便捷方法
 * @param channel 通道名称
 * @param handler 处理函数
 */
export function addHandler(channel: string, handler: (event: IpcMainInvokeEvent, ...args: any[]) => Promise<any> | any): void {
  ipcService.addHandler(channel, handler);
}

/**
 * 设置所有IPC处理程序的便捷方法
 */
export function setupIpcHandlers(): void {
  ipcService.setupHandlers();
}

/**
 * 移除所有IPC处理程序的便捷方法
 */
export function removeIpcHandlers(): void {
  ipcService.removeHandlers();
}
